package com.renit.gallery.fragments

import android.Manifest
import android.content.ContentValues
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.os.Bundle
import android.provider.MediaStore
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.core.graphics.drawable.toBitmap
import androidx.core.view.get
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import com.renit.gallery.PhotoItem
import com.renit.gallery.R
import com.renit.gallery.TAG
import com.renit.gallery.adapter.PagePhotoListAdapter
import com.renit.gallery.adapter.PagePhotoViewHolder
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class PhotoFragment : Fragment() {

    private var photoPages: ViewPager2? = null
    private var photoText: TextView? = null
    private var saveImage: ImageView? = null

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_photo, container, false)
    }

    override fun onStart() {
        super.onStart()

        photoPages = activity?.findViewById(R.id.photo_pages)
        photoText = activity?.findViewById(R.id.photo_text)
        saveImage = activity?.findViewById(R.id.save_img)

        val photoList = arguments?.getParcelableArrayList<PhotoItem>("PHOTO_LIST")

        PagePhotoListAdapter().apply {
            photoPages?.adapter = this
            submitList(photoList)
        }
        // 设置pages
        photoPages?.let {
            // 设置图片下面的文字
            it.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
                override fun onPageSelected(position: Int) {
                    super.onPageSelected(position)
                    photoText?.text = getString(R.string.photo_tag, (position + 1), photoList?.size)
                }
            })
            // 设置当前图片
            it.setCurrentItem(arguments?.getInt("PHOTO_POS") ?: 0, false)
        }
        // 设置下载
        saveImage?.setOnClickListener {
            viewLifecycleOwner.lifecycleScope.launch{saveImage()}
        }
    }

    private suspend fun saveImage() {
        withContext(Dispatchers.IO) {
            if (ContextCompat.checkSelfPermission(
                    requireContext(),
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                Log.e(TAG, "onStart: 没有下载权限")
                Toast.makeText(requireContext(), "没有权限", Toast.LENGTH_SHORT).show()
            } else {
                val holder = (photoPages?.get(0) as RecyclerView)
                    .findViewHolderForAdapterPosition(photoPages!!.currentItem) as PagePhotoViewHolder
                val bitmap = holder.photoDetails.drawable.toBitmap()
                val saveUri = requireContext().contentResolver.insert(
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    ContentValues()
                )?: kotlin.run {
                    MainScope().launch { Toast.makeText(requireContext(), "存储失败", Toast.LENGTH_SHORT).show() }
                    return@withContext
                }
                requireContext().contentResolver.openOutputStream(saveUri).use {
                    if (bitmap.compress(Bitmap.CompressFormat.JPEG, 90, it)) {
                        MainScope().launch { Toast.makeText(requireContext(), "保存成功", Toast.LENGTH_SHORT).show() }
                    } else {
                        MainScope().launch { Toast.makeText(requireContext(), "存储失败", Toast.LENGTH_SHORT).show() }
                    }
                    bitmap.recycle()
                }
            }
        }
    }
}